package com.everflourish.yeah100.act.statistics;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.entity.statistics.ClassStatisticInfo;
import com.everflourish.yeah100.http.ExaminationRequest;
import com.everflourish.yeah100.utils.ClassStatisticsUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/6.
 * 时间：2016/7/6
 */
public class FragmentTeacherClass extends BaseFragment {

    private TeacherStatisticsActivity mActivity;
    private ExaminationRequest mRequest;
    public ScrollView mScrollView;
    private float mTotalScore;
    // 各分数段人数textview
    private TextView m59NumberTv, m60NumberTv, m70NumberTv, m80NumberTv,
            m90NumberTv;
    private TextView m59pScoreTv, m60pScoreTv, m70pScoreTv, m80pScoreTv,
            m90pScoreTv;
    private TextView mPart59pScoreTv, mPart60pScoreTv, mPart70pScoreTv, mPart80pScoreTv,
            mPart90pScoreTv;
    // 柱形背景
    private View m59PillarBg, m60PillarBg, m70PillarBg, m80PillarBg,
            m90PillarBg;
    private int mPillarMaxHeight;
    // 班级统计部分
    private LinearLayout mClassStatisticsLL;
    // 分数统计部分
    public LinearLayout mScoreStatisticsLL;
    private List<ClassStatisticInfo> mClassStatisticInfoList = null;
    private ProgressWheel mProgress;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    private FrameLayout mResfreshFl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_teacher_class, container, false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initWidget();
        isPrepared = false;
    }

    private void initData() {
        mContext = mActivity = (TeacherStatisticsActivity) getActivity();
        mRequest = ExaminationRequest.getInstance();
        mPillarMaxHeight = (int) mActivity.getResources().getDimension(
                R.dimen.pillar_bg_max_height);
        mClassStatisticInfoList = new ArrayList<>();
    }

    private void initWidget() {
        mProgress = (ProgressWheel) getView().findViewById(R.id.statistics_class_progress);
//        mEmptyTv = (TextView) getView().findViewById(R.id.statistics_t_class_empty_tv);
        mResfreshFl = (FrameLayout) getView().findViewById(R.id.topic_refresh_fl);
        mScrollView = (ScrollView) getView().findViewById(R.id.data_view);
        m60NumberTv = (TextView) getView().findViewById(R.id.t_60_number);
        m70NumberTv = (TextView) getView().findViewById(R.id.t_70_number);
        m80NumberTv = (TextView) getView().findViewById(R.id.t_80_number);
        m90NumberTv = (TextView) getView().findViewById(R.id.t_90_number);
        m59NumberTv = (TextView) getView().findViewById(R.id.t_59_number);

        m90pScoreTv = (TextView) getView().findViewById(R.id.score_p_90);
        m80pScoreTv = (TextView) getView().findViewById(R.id.score_p_80);
        m70pScoreTv = (TextView) getView().findViewById(R.id.score_p_70);
        m60pScoreTv = (TextView) getView().findViewById(R.id.score_p_60);
        m59pScoreTv = (TextView) getView().findViewById(R.id.score_p_under_60);

        mPart90pScoreTv = (TextView) getView().findViewById(R.id.part_score_90_100);
        mPart80pScoreTv = (TextView) getView().findViewById(R.id.part_score_80_90);
        mPart70pScoreTv = (TextView) getView().findViewById(R.id.part_score_70_80);
        mPart60pScoreTv = (TextView) getView().findViewById(R.id.part_score_60_70);
        mPart59pScoreTv = (TextView) getView().findViewById(R.id.part_score_under_60);

        m60PillarBg = getView().findViewById(R.id.t_60_pillar_bg);
        m70PillarBg = getView().findViewById(R.id.t_70_pillar_bg);
        m80PillarBg = getView().findViewById(R.id.t_80_pillar_bg);
        m90PillarBg = getView().findViewById(R.id.t_90_pillar_bg);
        m59PillarBg = getView().findViewById(R.id.t_59_pillar_bg);

        // 班级统计
        mClassStatisticsLL = (LinearLayout) getView().findViewById(
                R.id.t_part_class_statistic);
        mScoreStatisticsLL = (LinearLayout) getView().findViewById(
                R.id.t_part_score_statistic);

        getClassStatisticsInfoRequest();
    }

    /**
     * 获取班级统计信息请求
     */
    private void getClassStatisticsInfoRequest() {
        mScrollView.setVisibility(View.VISIBLE);
        mResfreshFl.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.tClassStatisticsRequest(
                mActivity.mExamination.getId(), null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getClassStatisticsInfoListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取班级分析失败");
                        mProgress.setVisibility(View.GONE);
                        mResfreshFl.setVisibility(View.VISIBLE);
                        mScrollView.setVisibility(View.GONE);
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取班级分析监听
     *
     * @param response
     */
    private void getClassStatisticsInfoListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.EXAMINATION_RESULTS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ClassStatisticInfo>>() {
                }.getType();
                List<ClassStatisticInfo> classStatisticInfoList = gson
                        .fromJson(jsonArray.toString(), type);
                if (!response.isNull("totalScore")) {
                    mTotalScore = (float) response.getDouble("totalScore");
                }
                if (classStatisticInfoList == null
                        || classStatisticInfoList.size() == 0) {
                    // 获取学生成绩为空
//                    MyToast.showShort(mContext, "没有找到相关的统计信息");
                } else {
                    mClassStatisticInfoList.clear();
                    mClassStatisticInfoList.addAll(classStatisticInfoList);
                    setWidgetData();
                }
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.examination_08051_000012E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.examination_08052_300001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.examination_080599_999999E);
            } else {
                MyToast.showShort(mContext, "获取班级分析失败");
            }
        } catch (Exception e) {
            MyToast.showShort(mContext, "获取班级分析失败");
        } finally {
            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 设置控件数据
     */
    private void setWidgetData() {
        ClassStatisticsUtil classStatisticsUtil = new ClassStatisticsUtil(
                mClassStatisticInfoList);
        m90pScoreTv.setText((int) (mTotalScore * 0.9) + "~" + (int) mTotalScore + "分");
        m80pScoreTv.setText((int) (mTotalScore * 0.8) + "~" + (int) (mTotalScore * 0.9) + "分");
        m70pScoreTv.setText((int) (mTotalScore * 0.7) + "~" + (int) (mTotalScore * 0.8) + "分");
        m60pScoreTv.setText((int) (mTotalScore * 0.6) + "~" + (int) (mTotalScore * 0.7) + "分");
        m59pScoreTv.setText((int) (mTotalScore * 0.6) + "分以下");

        m59NumberTv.setText(classStatisticsUtil.getM59Number() + "");
        m60NumberTv.setText(classStatisticsUtil.getM60Number() + "");
        m70NumberTv.setText(classStatisticsUtil.getM70Number() + "");
        m80NumberTv.setText(classStatisticsUtil.getM80Number() + "");
        m90NumberTv.setText(classStatisticsUtil.getM90Number() + "");
        ViewGroup.LayoutParams m59Params = m59PillarBg.getLayoutParams();
        m59Params.height = (int) (mPillarMaxHeight * classStatisticsUtil
                .get59Ratio());
        m59PillarBg.setLayoutParams(m59Params);

        ViewGroup.LayoutParams m60Params = m60PillarBg.getLayoutParams();
        m60Params.height = (int) (mPillarMaxHeight * classStatisticsUtil
                .get60Ratio());
        m60PillarBg.setLayoutParams(m60Params);

        ViewGroup.LayoutParams m70Params = m70PillarBg.getLayoutParams();
        m70Params.height = (int) (mPillarMaxHeight * classStatisticsUtil
                .get70Ratio());
        m70PillarBg.setLayoutParams(m70Params);

        ViewGroup.LayoutParams m80Params = m80PillarBg.getLayoutParams();
        m80Params.height = (int) (mPillarMaxHeight * classStatisticsUtil
                .get80Ratio());
        m80PillarBg.setLayoutParams(m80Params);

        ViewGroup.LayoutParams m90Params = m90PillarBg.getLayoutParams();
        m90Params.height = (int) (mPillarMaxHeight * classStatisticsUtil
                .get90Ratio());
        m90PillarBg.setLayoutParams(m90Params);
        setClassStatisticsData();
        setScoreStatisticsData();
    }

    /**
     * 设置班级统计数据
     */
    private void setClassStatisticsData() {
        mClassStatisticsLL.removeAllViews();
        for (int i = 0; i < mClassStatisticInfoList.size(); i++) {
            View v = View.inflate(mContext,
                    R.layout.item_part_teacher_class_statistic, null);
            TextView classNameTv = (TextView) v
                    .findViewById(R.id.item_t_class_name);
            TextView classAvgScoreTv = (TextView) v
                    .findViewById(R.id.item_t_class_avg_score);
            TextView classMaxScoreTv = (TextView) v
                    .findViewById(R.id.item_t_class_max_score);
            TextView classMinScoreTv = (TextView) v
                    .findViewById(R.id.item_t_class_min_score);
            TextView classPassRateIv = (TextView) v.findViewById(R.id.item_t_class_pass_rate);
            LinearLayout itemLL = (LinearLayout) v.findViewById(R.id.item_ll);
            if (i % 2 == 1) {
                itemLL.setBackgroundDrawable(mContext.getResources()
                        .getDrawable(R.drawable.message_double_selector));
            } else {
                itemLL.setBackgroundDrawable(mContext.getResources()
                        .getDrawable(R.drawable.message_single_selector));
            }
            classNameTv.setText(mClassStatisticInfoList.get(i).getClassName());
            classAvgScoreTv.setText(mClassStatisticInfoList.get(i)
                    .getAvgScore());
            classMaxScoreTv.setText(mClassStatisticInfoList.get(i)
                    .getHighestScore());
            classMinScoreTv.setText(mClassStatisticInfoList.get(i)
                    .getLowestScore());
            classPassRateIv.setText(mClassStatisticInfoList.get(i).getPassRate() + "%");
            mClassStatisticsLL.addView(v);
        }
    }

    /**
     * 设置分数统计数据
     */
    private void setScoreStatisticsData() {
        mScoreStatisticsLL.removeAllViews();
        mPart90pScoreTv.setText((int) (mTotalScore * 0.9) + "\n|\n" + (int) mTotalScore + "\n分");
        mPart80pScoreTv.setText((int) (mTotalScore * 0.8) + "\n|\n" + (int) (mTotalScore * 0.9) + "\n分");
        mPart70pScoreTv.setText((int) (mTotalScore * 0.7) + "\n|\n" + (int) (mTotalScore * 0.8) + "\n分");
        mPart60pScoreTv.setText((int) (mTotalScore * 0.6) + "\n|\n" + (int) (mTotalScore * 0.7) + "\n分");
        mPart59pScoreTv.setText((int) (mTotalScore * 0.6) + "\n分\n以\n下");
        for (int i = 0; i < mClassStatisticInfoList.size(); i++) {
            View v = View.inflate(mContext,
                    R.layout.item_part_teacher_score_statistic, null);
            TextView classNameTv = (TextView) v
                    .findViewById(R.id.item_class_name);
            TextView score59Tv = (TextView) v
                    .findViewById(R.id.item_t_score_59);
            TextView score60Tv = (TextView) v
                    .findViewById(R.id.item_t_score_60);
            TextView score70Tv = (TextView) v
                    .findViewById(R.id.item_t_score_70);
            TextView score80Tv = (TextView) v
                    .findViewById(R.id.item_t_score_80);
            TextView score90Tv = (TextView) v
                    .findViewById(R.id.item_t_score_90);
            LinearLayout itemLL = (LinearLayout) v.findViewById(R.id.item_ll);
            if (i % 2 == 1) {
                itemLL.setBackgroundDrawable(mContext.getResources()
                        .getDrawable(R.drawable.message_double_selector));
            } else {
                itemLL.setBackgroundDrawable(mContext.getResources()
                        .getDrawable(R.drawable.message_single_selector));
            }
            classNameTv.setText(mClassStatisticInfoList.get(i).getClassName());
            score59Tv.setText(mClassStatisticInfoList.get(i)
                    .getSubtotalLessThan60() + "人");
            score60Tv.setText(mClassStatisticInfoList.get(i)
                    .getSubtotal60To70() + "人");
            score70Tv.setText(mClassStatisticInfoList.get(i)
                    .getSubtotal70To80() + "人");
            score80Tv.setText(mClassStatisticInfoList.get(i)
                    .getSubtotal80To90() + "人");
            score90Tv.setText(mClassStatisticInfoList.get(i)
                    .getSubtotal90To100() + "人");
            mScoreStatisticsLL.addView(v);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}